package com.dwxt.redis.listener;

import com.dwxt.redis.service.feign.OrderService;
import com.dwxt.redis.service.feign.RaceOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * 监听
 * 所有db的过期事件__keyevent@*__:expired"
 */
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    //商城服务
    @Autowired
    private OrderService orderService;
    //库存增加
    @Autowired
    private RaceOrderService raceOrderService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 针对 redis 数据失效事件，进行数据处理
     *
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取到失效的 key，进行取消订单业务处理
        String expiredKey = message.toString();
        if (expiredKey.startsWith("mall_")) {
            System.out.println(expiredKey);
            String orderId = expiredKey.substring(5);
            orderService.cancelOrder(orderId);
        }else if (expiredKey.startsWith("race_order_zfb")){
            System.out.println(expiredKey);
            String orderId = expiredKey.substring(14);
            raceOrderService.timeoutPayBack(orderId);
        }else if (expiredKey.startsWith("race_order_wx")){
            System.out.println(expiredKey);
            String orderId = expiredKey.substring(13);
            raceOrderService.timeoutPayBack(orderId);
        }
    }
}